import { ObjectId } from '@fastify/mongodb'
import ret from '../ret.mjs'

export default function (fastify, opts, done) {
  //分页查询
  fastify.post('/:table/findpage', async function (req) {
    try {
      let table = req.params.table
      let query = req.body.query

      let tb = this.mongo.db
        .collection(table)
        .find(query)
        .skip((req.body.pageindex - 1) * req.body.pagesize)
        .limit(req.body.pagesize)

      if (req.body.order) {
        tb.sort(req.body.order)
      }

      if (req.body.project) {
        tb.project(req.body.project)
      }

      let count = 0
      if (Object.keys(query).length === 0) {
        count = await this.mongo.db.collection(table).estimatedDocumentCount()
      } else {
        count = await this.mongo.db.collection(table).countDocuments(query)
      }

      return ret.success({
        list: await tb.toArray(),
        count
      })
    } catch (err) {
      return ret.error(err.message)
    }
  })

  //不分页查询 可以限制数量查询
  fastify.post('/:table/findlimit', async function (req) {
    try {

      let tb = this.mongo.db.collection(req.params.table).find(req.body.query)

      if (req.body.limit) {
        tb.limit(req.body.limit)
      }

      if (req.body.order) {
        tb.sort(req.body.order)
      }

      if (req.body.project) {
        tb.project(req.body.project)
      }

      return ret.success(await tb.toArray())
    } catch (err) {
      return ret.error(err.message)
    }
  })

  //不分页查询全部
  fastify.post('/:table/findall', async function (req) {
    try {

      if (!req.body.query) req.body.query = {}
      let tb = this.mongo.db.collection(req.params.table).find(req.body.query)

      if (req.body.order) {
        tb.sort(req.body.order)
      }

      if (req.body.project) {
        tb.project(req.body.project)
      }

      return ret.success(await tb.toArray())
    } catch (err) {
      return ret.error(err.message)
    }
  })

  //查询单条数据
  fastify.post('/:table/findone', async function (req) {
    try {

      if (!req.body.query) req.body.query = {}
      let tb = this.mongo.db.collection(req.params.table)     

      if (req.body.project) {
        tb.project(req.body.project)
      }

      return ret.success(await tb.findOne(req.body.query))
    } catch (err) {
      return ret.error(err.message)
    }
  })

  //查询count
  fastify.post('/:table/findcount', async function (req) {
    try {
      let table = req.params.table
      let query = req.body.query
      let count = 0
      if (Object.keys(query).length === 0) {
        count = await this.mongo.db.collection(table).estimatedDocumentCount()
      } else {
        count = await this.mongo.db.collection(table).countDocuments(query)
      }
      return ret.success(count)
    } catch (err) {
      return ret.error(err.message)
    }
  })

  //向表插入数据
  fastify.post('/:table/insert', async function (req) {
    try {
      // console.time('insert')
      let table = req.params.table
      if (!req.body.createat) {
        let d = new Date()
        req.body.createat = d.valueOf()
        if (req.body._id == null || req.body._id == '') {
          delete req.body._id
        }
      }
      let data = await this.mongo.db.collection(table).insertOne(req.body)
      // console.timeEnd('insert')
      return ret.success(data)
    } catch (err) {
      return ret.error(err.message)
    }
  })

  //向表插入多条数据
  fastify.post('/:table/insertmany', async function (req) {
    try {
      let table = req.params.table
      req.body.forEach(element => {
        if (!element.hasOwnProperty('createat')) {
          let d = new Date()
          element.createat = d.valueOf()
          if (element._id == null || element._id == '') {
            delete element._id
          }
        }
      })
      let data = await this.mongo.db.collection(table).insertMany(req.body)
      return ret.success(data)
    } catch (err) {
      return ret.error(err.message)
    }
  })

  //修改单条数据
  fastify.put('/:table/update', async function (req) {
    try {

      let table = req.params.table
      let item = req.body

      let _id = item._id
      if (/^\d+$/.test(item._id)) {
        _id = parseInt(item._id)
      } else if (ObjectId.isValid(item._id)) {
        _id = new ObjectId(item._id)
      }
      delete item._id
      let d = new Date()
      item.updateat = d.valueOf()
      let data = await this.mongo.db.collection(table).updateOne(
        {
          _id
        },
        {
          $set: item
        }
      )
      return ret.success(data)
    } catch (error) {
      return ret.error(err.message)
    }
  })

  //修改多条数据
  fastify.put('/:table/updatemany', async function (req) {
    try {

      let table = req.params.table
      let query = req.body.query
      let update = req.body.update

      let d = new Date()
      update.updateat = d.valueOf()

      let data = await this.mongo.db.collection(table).updateMany(
        query,
        {
          $set: update
        }
      )
      return ret.success(data)
    } catch (error) {
      return ret.error(err.message)
    }
  })

  //根据查询删除多条数据
  fastify.post('/:table/deletemany', async function (req) {
    try {
      console.log(req.body)

      let table = req.params.table
      let data = await this.mongo.db.collection(table).deleteMany(req.body)
      return ret.success(data)
    } catch (error) {
      return ret.error(err.message)
    }
  })

  //根据id删除表的数据
  fastify.delete('/:table/:id', async function (req) {
    try {

      let table = req.params.table
      let _id = req.params.id
      //req.params全部为字符串类型
      //用正则表达式判断id字符串是否为数字，如果是数字转数字类型
      if (/^\d+$/.test(_id)) {
        _id = parseInt(_id)
      } else if (ObjectId.isValid(req.params.id)) {
        _id = new ObjectId(req.params.id)
      }

      let data = await this.mongo.db.collection(table).deleteOne({
        _id
      })
      return ret.success(data)
    } catch (error) {
      return ret.error(err.message)
    }
  })

  //根据id取单条数据
  fastify.get('/:table/:id', async function (req) {
    try {

      let table = req.params.table
      let _id = req.params.id
      //req.params全部为字符串类型
      //用正则表达式判断id字符串是否为数字，如果是数字转数字类型
      if (/^\d+$/.test(_id)) {
        _id = parseInt(_id)
      } else if (ObjectId.isValid(req.params.id)) {
        _id = new ObjectId(req.params.id)
      }
      let data = await this.mongo.db.collection(table).findOne({
        _id
      })
      return ret.success(data)
    } catch (error) {
      return ret.error(err.message)
    }
  })

  //根据id取单条数据,并在指定字段上加计数加1
  fastify.get('/:table/foau_:column/:id', async function (req) {
    try {
      let table = req.params.table
      let _id = req.params.id
      let update = {}
      update['$inc']= {}
      update['$inc'][req.params.column]=1
      console.log('update', update)
      //req.params全部为字符串类型
      //用正则表达式判断id字符串是否为数字，如果是数字转数字类型
      if (/^\d+$/.test(_id)) {
        _id = parseInt(_id)
      } else if (ObjectId.isValid(req.params.id)) {
        _id = new ObjectId(req.params.id)
      }
      let data = await this.mongo.db.collection(table).findOneAndUpdate({
        _id
      },update)
      return ret.success(data.value)
    } catch (error) {
      return ret.error(err.message)
    }
  })

  //根据表名取表的数字自增id
  fastify.get('/:table/id', async function (req) {
    try {

      let table = req.params.table
      let seqTable = 'seq'
      let r = await this.mongo.db.collection(seqTable).findOneAndUpdate(
        {
          _id: table
        },
        {
          $inc: {
            i: 1
          }
        }
      )

      if (r.value) {
        return ret.success(r.value.i)
      } else {
        let data = await this.mongo.db.collection(seqTable).insert({
          _id: table,
          i: 2
        })
        if (data.i) {
          return ret.success(data.i)
        } else {
          return ret.success(1)
        }
      }
    } catch (error) {
      return ret.error(err.message)
    }
  })

  done()
}

